package com.ecoolex.chinadutyfree.retailer.api.graphql;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.lang.NonNull;

import com.ecoolex.chinadutyfree.retailer.api.core.ApiConstant;
import com.ecoolex.chinadutyfree.retailer.entity.UserExternalInfo;
import com.ecoolex.chinadutyfree.retailer.ws.UnionPayStoreService;
import com.ecoolex.framework.common.pojo.Entry;
import com.ecoolex.framework.common.util.BeanUtil;
import com.ecoolex.framework.modularize.api.auth.user.ConsumerMemberAuthority;
import com.ecoolex.framework.modularize.api.service.device.DeviceInfo;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module;
import com.ecoolex.framework.web.api.graphql2.annotation.QueryField;
import com.ecoolex.framework.web.api.graphql2.annotation.GraphQL2Module.Type;
import com.ecoolex.user.system.entity.UserLoginRecord;
import com.ecoolex.user.system.entity.UserRoot;
import com.ecoolex.user.system.enums.UserLoginSource;
import com.ecoolex.user.system.enums.UserOperLogType;
import com.ecoolex.user.system.enums.UserRootSource;
import com.ecoolex.user.system.pojo.LoginUserRoot;
import com.ecoolex.user.system.ws.UserSystemService;

@GraphQL2Module(type = Type.User,description = "银联国际用户")
public class UserGraphql {
	
	@Reference
	private UnionPayStoreService unionPayStoreService;
	
	@Reference
    private UserSystemService userSystemService;

	@QueryField(field = "unionPayLogin", description = "银联国际用户登录")
	public LoginUserRoot userLogin(@NonNull String externalUserId,DeviceInfo deviceInfo, ConsumerMemberAuthority user) {
		UserRoot root;
		//不存在则注册
		if(!unionPayStoreService.existByExternalUserId(externalUserId)) {
			root = userSystemService.authorizationRegister(UserRootSource.THIRD_PARTY,"UnionPay",null,null,ApiConstant.PROJECT_API_NAME);
			unionPayStoreService.addUserExternalInfo(root.getUserId(), externalUserId, root.getUserName());
			// 登录
	        UserLoginRecord record = userSystemService.login(root.getUserId(), UserLoginSource.THIRD_PARTY_API, "UnionPay", deviceInfo, ApiConstant.PROJECT_API_NAME);
	        // 刷新token
	        user.refresh(record.getToken());
	        // 操作日志
	        user.operationLog(UserOperLogType.REGISTER.real(), "银联国际自动注册", Entry.create("user", root));
		}else {
			UserExternalInfo userExternalInfo = unionPayStoreService.getByExternalUserId(externalUserId);
			root = userSystemService.getUserRootByUserId(userExternalInfo.getUserId());
			// 登录
	        UserLoginRecord record = userSystemService.login(root.getUserId(), UserLoginSource.THIRD_PARTY_API, "UnionPay", deviceInfo, ApiConstant.PROJECT_API_NAME);
	        // 刷新token
	        user.refresh(record.getToken());
		}
		
        LoginUserRoot loginUserRoot = new LoginUserRoot();
        loginUserRoot.setLoginSource(UserLoginSource.THIRD_PARTY_API);
        return BeanUtil.copy(root, loginUserRoot);
	}
}
